<?php
/**
 * Created by PhpStorm.
 * User: Charles
 * Date: 2017/10/8
 * Time: 0:32
 */

namespace app\Http\Controllers\Wechat;


use App\Http\Controllers\Controller;
use App\Models\Domain;
use App\Models\EasyWechat;
use App\Models\UniqidOpenid;
use Illuminate\Http\Request;

class ApiController extends Controller
{
    public function getIndex(Request $request)
    {
        return EasyWechat::getApp()->server->serve();
    }

    public function postIndex(Request $request)
    {
        EasyWechat::getApp()->server->setMessageHandler(function ($message) {
            $openid = $message->FromUserName;
            switch ($message->MsgType) {
                case 'event':
                    return '';
                    break;
                case 'text':
                    $oneDomain = Domain::one();
                    switch ($message->Content) {
                        case '上传':
                            $uniqidOpenid = UniqidOpenid::query()
                                ->where('openid', $openid)
                                ->orderBy('id', 'desc')
                                ->first();
                            if (null === $uniqidOpenid) {
                                $uniqidOpenid = new UniqidOpenid();
                                $uniqidOpenid->openid = $openid;
                                $uniqidOpenid->uniqid = uniqid('', true);
                                $uniqidOpenid->save();
                            }
                            $uniqid = $uniqidOpenid->uniqid;
                            $url =  "http://{$oneDomain}/wechat/upload?wechat_uniqid=" . $uniqid;
                            return wechat_short_url($url);
                            break;
                        case '用户中心':
                            return "http://{$oneDomain}/wechat/member-center";
                    }
                    return '收到您的意见和建议';
                    break;
                case 'image':
                    return '';
                    break;
                case 'voice':
                    return '';
                    break;
                case 'video':
                    return '';
                    break;
                case 'location':
                    return '';
                    break;
                case 'link':
                    return '';
                    break;
                // ... 其它消息
                default:
                    return '';
                    break;
            }
            return '';
        });
        return EasyWechat::getApp()->server->serve();
    }

    public function getTest(Request $request)
    {

    }
}